#!/usr/bin/env node

/**
 * 处理markdown文件到普通格式
 */
const utils = require('./utils');
const fs = require('fs');
const matter = require('gray-matter');
const parser = require('./convert');
const rimraf = require('rimraf');
const path = require('path');
const fsextra = require('fs-extra');
const chalk = require('chalk');

require('events').EventEmitter.defaultMaxListeners = 80;

const root = process.cwd();

const mdFiles = [];
const mdPath = process.argv[2] ? path.resolve(root, process.argv[2]) : `${utils.rootPath}/md`;
const pdfPath = process.argv[3] ? path.resolve(root, process.argv[3]) : `${utils.rootPath}/pdf`;
const tmpPath = `${utils.rootPath}/tmp`;

// console.log(process.argv, mdPath, pdfPath, tmpPath);

// process.exit(1);
console.log('准备程序正在装载...');
// clean
rimraf.sync(pdfPath);
rimraf.sync(tmpPath);

if(!fs.existsSync(mdPath)) {
    fs.mkdirSync(mdPath);
}

if (!fs.existsSync(pdfPath)) {
    fs.mkdirSync(pdfPath);
}

if (!fs.existsSync(tmpPath)) {
    fs.mkdirSync(tmpPath);
}

// copy
copyWorkspace();

utils.fetchMarkdownFiles(path.resolve(tmpPath), mdFiles);

// 需要处理的markdown文件
// console.log(mdFiles)

for (const md of mdFiles) {
    // 处理front matter
    splitFrontMatter(md)
}

doParse(mdFiles);

function splitFrontMatter(md) {
    md.meta = matter.read(md.path);
    // console.log(md.meta);
    //overwrite file
    fs.writeFileSync(md.path, md.meta.content);
}

function copyWorkspace() {
    console.log('正在骇入vuepress...');
    fsextra.copySync(`${mdPath}`, `${tmpPath}`, {
        filter: function (src, dest) {
            // console.log(src, dest);
            if (src.includes('.vuepress')) return false;
            return true;
        }
    });
}

async function doParse(mdFiles) {
    for (const md of mdFiles) {
        await parser.parse(md, {
            mdPath,
            pdfPath
        });
    }
}

// rimraf.sync(tmpPath);
